package com.leather.admin.myrealm;

import com.leather.admin.entity.Admin;
import com.leather.admin.service.AdminService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyReam extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();

        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        List<String> permissions = adminService.getAdminPermission(name);
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户信息
        String name = authenticationToken.getPrincipal().toString();
        String password = String.valueOf((char[]) authenticationToken.getCredentials());
        if (StringUtils.isBlank(password)) {
            throw new UnknownAccountException("密码不能为空");
        }
        Admin admin = adminService.getAdminById(name);
        if (admin == null) {
            throw new UnknownAccountException("用户名错误");
        }
        if (!password.equals(admin.getPassword())) {
            throw new UnknownAccountException("密码错误");
        }
        if (admin.getFlag() == 1) {
            throw new LockedAccountException("该用户已被冻结");
        }
        //这里验证authenticationToken和simpleAuthenticationInfo的信息
        return new SimpleAuthenticationInfo(name, admin.getPassword(), getName());
    }

}
